#include "dvbinner.h"
#include "dvbtdt.h"

dvb_time_t stGMTTime;
unsigned char u8TDTTaskRun = 0;

static void DVBRecvTDTTask(void *params)
{
	static int counter=9;
	int ret,ptr=0;
	unsigned short Secchar[16];
	dvb_handle_t hFilter,hMsgque;
	char	section[1024];
	unsigned int oldtick,newtick;
	unsigned int UTCTime=0x0;
	unsigned short MJDDate=0;
	filter_param_t filterParam;	
	int i =0;
	unsigned char mask[8],data[8];

	hMsgque=mwOsCreateMessage(5,1024);
	mask[0]=0xE0;
	data[0]=SIPSI_TID_TDT;
	memset(Secchar,0,16*2);
	for (i=0;i<1;i++)
		Secchar[i]=data[i] + (mask[i]<<8);
	filterParam.m_u8CrcCheck = 0;
	filterParam.m_u8FilterDepth = 1;
	filterParam.m_pfCb = NULL;	
	filterParam.m_u16Pid = SIPSI_PID_TDTTOT;
	filterParam.m_pu16SectByte = Secchar;
	filterParam.m_hQueueID = hMsgque;
	mwDebug("mwDmxStartFilter  tdt hMsgque%d\n",hMsgque);
	ret=mwDmxStartFilter(&filterParam,&hFilter);
	if (ret!=0)
	{
		mwError("[SI] DvbRecvTDT_Task start filter fail*********************\r\n");
		mwOsDeleteMessage(hMsgque);
		return;
	}
	oldtick=mwOsGetTickCount();
	while (u8TDTTaskRun == 1)
	{
		if (mwOsReceiveMessage(hMsgque, section,1024,30000)==0)
		{
			if(section[0]==SIPSI_TID_TDT)//TDT
			{
				SiPsiTDTTOTGetUTCTime(section,&MJDDate,&UTCTime);		
				SiPsiConvertToSysTime((sipsi_systime_t*)&stGMTTime, MJDDate,UTCTime);
				counter++;
				if (counter==5)
				{
					//mwDebug("Receive TDT %02d:%02d:%02d \r\n",stGMTTime.hour, stGMTTime.minute,stGMTTime.second);
					counter=0;
				}
				oldtick=mwOsGetTickCount();
			}
			else if(section[0]==SIPSI_TID_TOT)//ToT
			{	
				int count;
				SiPsiTDTTOTGetUTCTime(section,&MJDDate,&UTCTime);
				SiPsiConvertToSysTime((sipsi_systime_t*)&stGMTTime, MJDDate,UTCTime);	
				oldtick=mwOsGetTickCount();
			}
			mwOsSleep(5*100);
		}	
		else
		{
			mwDebug("********NO Receive TDT ******\r\n");
			newtick=mwOsGetTickCount();
			stGMTTime = GetEndTime(stGMTTime, (newtick-oldtick)/100);
			oldtick=newtick;
		}
	}
	mwDmxStopFilter(hFilter);
	mwOsDeleteMessage(hMsgque);
	return;
}

dvb_time_t DVBTDTGetGMTTime()
{
	dvb_time_t stTime;

	memcpy(&stTime, &stGMTTime, sizeof(stGMTTime));

	return stTime;
}

int DVBTDTInit()
{
	dvb_handle_t  TdtTaskHandle;
	int ret;
	dvb_time_t initstGMTTime = {1980,01,01,01,00,00,00};
	
	stGMTTime = initstGMTTime;
	ret=mwOsCreateTask("TDTTASK", 1, 0x8000, &TdtTaskHandle, TRUE, DVBRecvTDTTask, NULL);
	if(ret !=0)
	{
		mwError("DvbTdtInit() - create task failed\r\n");	
	}
	return ret;
}

int DVBTDTDeinit()
{
	
}

